package org.com.creationalPattern.singleton;

/**
 * 单例模式测试
 * @author Jonny
 * @version 1.0
 * @Description:
 * @date 2021/4/13 16:30
 */
public class SingletonDemo {
    public static void main(String[] args) {
        NumThread threadA=new NumThread("线程A");
        threadA.start();
        NumThread threadB=new NumThread("线程B");
        threadB.start();
    }


}

class GlobalNum{
    private static GlobalNum _globalNum=null;
    private int num=0;
    public GlobalNum(){

    }
    synchronized public static GlobalNum getInstance(){
        if(_globalNum==null){
            _globalNum=new GlobalNum();
        }
        return _globalNum;
    }
    public synchronized int getNum(){
        return ++num;
    }
}

class NumThread extends Thread{
    private String ThreadName;

    public NumThread(String name){
        ThreadName=name;
    }

    public void run(){
        GlobalNum glnb=GlobalNum.getInstance();

        //for循环显示访问次数
        for (int i=0;i<5;i++){
            System.out.println(ThreadName+" 第"+glnb.getNum()+"次访问");
            try{
                this.sleep(1000);
            }catch (Exception ex){
                ex.printStackTrace();
            }
        }
    }

}
